package com.example.exam.controller.fileController;

import com.example.exam.service.utils.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.logging.Logger;

/**
 * @author zhang
 */
@RestController
@RequestMapping("/download")
@ApiIgnore
public class DownloadController {
    @Autowired
    private FileService fileServiceImpl;
    //下载模板文件
    @GetMapping("/{filename}")
    public void download(@PathVariable String filename, HttpServletResponse response) {
        File file = new File(fileServiceImpl.getPath(filename));
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
        try {
            InputStream is = Files.newInputStream(file.toPath());
            OutputStream os = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
        } catch (IOException e) {
            Logger.getGlobal().info(e.getMessage());
        }
    }
}
